package com.chen.gulimall.gulimallproduct.service.impl;

import com.chen.gulimall.gulimallproduct.entity.SkuImagesEntity;
import com.chen.gulimall.gulimallproduct.service.*;
import com.chen.gulimall.gulimallproduct.vo.SkuItemSaleAttrVo;
import com.chen.gulimall.gulimallproduct.vo.SkuItemVo;
import com.chen.gulimall.gulimallproduct.vo.SpuItemAttrGroupVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.gulimallcommon.common.utils.PageUtils;
import com.chen.gulimallcommon.common.utils.Query;

import com.chen.gulimall.gulimallproduct.dao.SkuInfoDao;
import com.chen.gulimall.gulimallproduct.entity.SkuInfoEntity;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    SpuInfoDescService descService;

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    AttrGroupService attrGroupService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    ThreadPoolExecutor executor;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {

        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<SkuInfoEntity>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and(item-> {
                item.eq("sku_id",key).or().like("sku_name",key);
            });
        }

        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
           wrapper.eq("catalog_id",catelogId);
        }

        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
            wrapper.eq("brand_id",brandId);
        }

        String min = (String) params.get("min");
        if (!StringUtils.isEmpty(min)) {
            wrapper.ge("price",min);
        }

        String max = (String) params.get("max");
        if (!StringUtils.isEmpty(max)) {
            //此次保证max默认为0时则不执行此语句，让数据库查询出全部数据，只有比0大时才做处理
            BigDecimal bigDecimal = new BigDecimal(max);
            if (bigDecimal.compareTo(new BigDecimal("0")) == 1) {
                wrapper.le("price",max);
            }
        }


        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public SkuItemVo getSkuItem(Long skuId) {

        SkuItemVo skuItemVo = new SkuItemVo();

        CompletableFuture<SkuInfoEntity> future = CompletableFuture.supplyAsync(()->{
            //获取商品sku的基本信息
            skuItemVo.setInfo(getById(skuId));
            return skuItemVo.getInfo();
        },executor);


        CompletableFuture<Void> future1 = future.thenAcceptAsync((res) -> {
            //设置spu的详细信息
            skuItemVo.setDesc(descService.getById(res.getSpuId()));
        }, executor);


        CompletableFuture<Void> future2 = future.thenAcceptAsync((res) -> {
            Long catalogId = res.getCatalogId();
            Long spuId = res.getSpuId();
            //设置spu对应的属性组以及属性值
            List<SpuItemAttrGroupVo> spuItemAttrGroupVos = attrGroupService.getGroupAttrForSpu(spuId, catalogId);
            skuItemVo.setGroupAttrs(spuItemAttrGroupVos);
        }, executor);

        CompletableFuture<Void> future3 = future.thenAcceptAsync((res) -> {
            //设置对应spu的销售类型
            List<SkuItemSaleAttrVo> saleVos = skuSaleAttrValueService.getSaleAttrAndValue(res.getSpuId());
            skuItemVo.setSaleAttr(saleVos);
        }, executor);

        CompletableFuture<Void> imageAsync = CompletableFuture.runAsync(() -> {
            //设置sku的所有图片集
            List<SkuImagesEntity> images = skuImagesService.getSkuImages(skuId);
            skuItemVo.setImages(images);
        }, executor);

        try {
            //此方法表示让几个线程阻塞等待，直到执行成功,否则可能会提前返回skuItemVo的值
            CompletableFuture.allOf(future1,future2,future3,imageAsync).get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        return skuItemVo;
    }

}